const fs = require('fs');
const path = require('path');
const mysql = require('mysql2/promise');
const config = require('./database-config.js');

// 映射：CSV列顺序 → 槽位编号（CSV顺序: 头盔, 项链, 武器, 护腕, 铠甲, 战靴）
const slotNumByHeader = { '头盔': 1, '项链': 4, '武器': 2, '护腕': 5, '铠甲': 3, '战靴': 6 };
const headersInOrder = ['头盔', '项链', '武器', '护腕', '铠甲', '战靴'];

function parseCsv(filePath) {
    const raw = fs.readFileSync(filePath, 'utf8').split(/\r?\n/);
    const rows = [];
    for (const line of raw) {
        if (!line || /^\s*$/.test(line)) continue;
        const cols = line.split(',');
        if (cols.length < 8) continue;
        const gemNameCell = cols[0].trim();
        if (!gemNameCell || gemNameCell === '宝石' || gemNameCell.startsWith('备注')) continue;
        const attrName = cols[1].trim();
        const slotMarks = cols.slice(2, 8);
        const gemNames = gemNameCell.split('、').map(s => s.trim()).filter(Boolean);
        for (const gemName of gemNames) {
            rows.push({ gemName, attrName, slotMarks });
        }
    }
    return rows;
}

function computeSlotsFromMarks(slotMarks) {
    const slots = [];
    for (let i = 0; i < headersInOrder.length; i++) {
        const head = headersInOrder[i];
        const mark = (slotMarks[i] || '').trim();
        if (mark) slots.push(slotNumByHeader[head]);
    }
    return Array.from(new Set(slots)).sort((a, b) => a - b);
}

async function main() {
    const csvPath = path.resolve(__dirname, 'output/宝石说明.csv');
    const rows = parseCsv(csvPath);
    const conn = await mysql.createConnection(config.source);
    const diffs = [];
    const missingGems = new Set();
    const missingAttrs = [];
    try {
        for (const row of rows) {
            const expectedSlots = computeSlotsFromMarks(row.slotMarks);
            const expectedStr = expectedSlots.join(',');
            const [gemRows] = await conn.execute('SELECT id FROM gem_base WHERE name = ? LIMIT 1', [row.gemName]);
            if (!gemRows || gemRows.length === 0) {
                missingGems.add(row.gemName);
                continue;
            }
            const gemId = gemRows[0].id;
            const [attrRows] = await conn.execute('SELECT id, equipment_slots FROM gem_attributes WHERE gem_id = ? AND attribute_name = ? LIMIT 1', [gemId, row.attrName]);
            if (!attrRows || attrRows.length === 0) {
                missingAttrs.push({ gemName: row.gemName, attrName: row.attrName });
                continue;
            }
            const actual = (attrRows[0].equipment_slots || '').split(',').filter(Boolean).map(s => s.trim()).sort((a, b) => a - b).join(',');
            if (actual !== expectedStr) {
                diffs.push({ gemName: row.gemName, attrName: row.attrName, expected: expectedStr, actual });
            }
        }

        console.log('📋 差异清单:');
        if (diffs.length === 0) console.log('  ✅ 无差异');
        diffs.forEach(d => console.log(`  ❌ ${d.gemName} - ${d.attrName}: 期望 ${d.expected} 实际 ${d.actual}`));

        if (missingGems.size > 0) {
            console.log('\n⚠️ 未找到的宝石名称:');
            Array.from(missingGems).forEach(n => console.log(`  - ${n}`));
        }
        if (missingAttrs.length > 0) {
            console.log('\n⚠️ 缺失属性记录:');
            missingAttrs.forEach(x => console.log(`  - ${x.gemName} - ${x.attrName}`));
        }
    } finally {
        await conn.end();
    }
}

if (require.main === module) {
    main().catch(err => { console.error('❌ 失败:', err?.message || err); process.exit(1); });
}


